package org.turl.utils;

import org.turl.wrappers.Wrapper;

import java.util.*;
import java.lang.reflect.Constructor;

/**
 * Created by tonyx
 * User: tonyx
 * Date: May 22, 2008
 * Time: 6:24:36 PM
 */
public class ConversionMap {

    private Map<ConstructorPairAndContractClass,Wrapper> mapperWrappers =  new HashMap<ConstructorPairAndContractClass,Wrapper>();

    private static ConversionMap instance;
    public static synchronized ConversionMap getInstance() {
        if (instance==null) {
            instance= new ConversionMap();
        }
        return instance;
    }

    private ConversionMap() {
    }

    public void setMapper(Constructor origin, Constructor target, Class contractClass, Wrapper wrapper) {
        ConstructorPairAndContractClass constructorPair = new ConstructorPairAndContractClass(origin,target,contractClass);
        mapperWrappers.put(constructorPair,wrapper);
    }

    public void setMapper(ConstructorPairAndContractClass originAndTarget, Wrapper wrapper) {
        mapperWrappers.put(originAndTarget,wrapper);
    }

    public Object getMappedInstance(Constructor origin, Constructor target, Class contractClass, Object[] params) {
        Wrapper wrapper = mapperWrappers.get(new ConstructorPairAndContractClass(origin,target,contractClass));
        Object[] wrappedParams = wrapper.wrap(params);
        try {
            return target.newInstance(wrappedParams);
        } catch (Exception e) {
            throw new RuntimeException(e) ;
        }
    }
}

